package com.xwtec.cor.v3;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zt
 * @Date: 2021/2/25 21:31
 */
public class Servlet_Main {

    public static void main(String[] args) {
        Request request = new Request();
        request.str = "大家好(:,<script>我是 mashibing.com,都是996";
        Response response = new Response();
        response.str="";
        ChainFilter chainFilter = new ChainFilter();
        chainFilter.add(new HtmlFilter()).add(new WebFilter());
        chainFilter.doFilter(request,response,chainFilter);
        System.out.println(request.str);
        System.out.println(response.str);
    }



}
class Request{
    String str;
}

class Response{
    String str;
}

interface Filter {
    boolean doFilter(Request request,Response response,ChainFilter chain);
}

class HtmlFilter implements Filter{

    @Override
    public boolean doFilter(Request request, Response response, ChainFilter chain) {
        //第一个filter处理 request
        String str = request.str;
        String s = str.replaceAll("<", "[").replaceAll(">", "]");
        request.str = s;
        chain.doFilter(request,response,chain);
        //第一个filter 处理response
        response.str +="----HtmlFilter";

        return true;
    }
}

class WebFilter implements Filter{

    @Override
    public boolean doFilter(Request request, Response response, ChainFilter chain) {
        //第二个filter处理 request
        String str = request.str;
        request.str = str.replace("mashibing.com", "www.mashibing.com");

        chain.doFilter(request,response,chain);
        //第一个filter 处理response
        response.str +="----WebFilter";

        return true;
    }
}

class ChainFilter implements Filter{

    List<Filter> filters = new ArrayList<Filter>();

    //定义一个标记索引
    int index = 0;
    public ChainFilter add(Filter filter){
        filters.add(filter);
        return this;
    }


    @Override
    public boolean doFilter(Request request, Response response, ChainFilter chain) {
        //如果这个标记索引的值和 过滤器的filter相等，就不再执行
        if (index == filters.size()) return false;
        Filter f = filters.get(index);
        index++;

        return f.doFilter(request,response,chain);
    }
}

